<template>
    <main class="min-h-screen bg-base-100 p-4">
        <div class="max-w-7xl mx-auto">
            <!-- 页面标题 -->
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-base-content">
                        联系人管理
                    </h1>
                    <p class="text-sm text-gray-500 mt-1">
                        管理所有业务联系人信息
                    </p>
                </div>
                <div class="flex gap-2">
                    <button
                        @click="refreshData"
                        class="btn btn-outline btn-sm"
                        :disabled="loading"
                    >
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            :class="{ 'animate-spin': loading }"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                            />
                        </svg>
                        刷新
                    </button>
                    <button @click="addContact" class="btn btn-primary btn-sm">
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                            />
                        </svg>
                        新增联系人
                    </button>
                </div>
            </div>

            <!-- 错误提示 -->
            <div v-if="error" class="alert alert-error mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ error }}</span>
                <button @click="loadContacts(1)" class="btn btn-ghost btn-sm">
                    重试
                </button>
            </div>

            <!-- 搜索区域 -->
            <div class="card bg-base-200 shadow-sm mb-6">
                <div class="card-body">
                    <h2 class="card-title text-lg mb-4">
                        <!-- 图标 -->
                        搜索条件
                    </h2>
                    <div
                        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end"
                    >
                        <!-- 联系人姓名搜索 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >联系人姓名</span
                                >
                            </label>
                            <input
                                v-model="searchParams.name"
                                type="text"
                                placeholder="输入联系人姓名..."
                                class="input input-bordered"
                                @keyup.enter="searchContacts"
                            />
                        </div>

                        <!-- 动态公司搜索 -->
                        <div class="form-control relative">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >所属公司</span
                                >
                            </label>
                            <input
                                v-model="companySearchText"
                                type="text"
                                placeholder="输入公司名称搜索..."
                                class="input input-bordered"
                                @input="handleCompanySearch"
                                @focus="showCompanyDropdown = true"
                                @blur="hideCompanyDropdown"
                                @keyup.enter="searchContacts"
                            />

                            <!-- 下拉选择框 -->
                            <div
                                v-show="
                                    showCompanyDropdown &&
                                    filteredCompanies.length > 0 &&
                                    !companyLoading
                                "
                                class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 max-h-60 overflow-auto"
                                style="top: 100%"
                            >
                                <div
                                    v-for="company in filteredCompanies"
                                    :key="company.id"
                                    class="px-4 py-2 hover:bg-base-200 cursor-pointer transition-colors"
                                    @mousedown="selectCompany(company)"
                                >
                                    {{ company.name }}
                                </div>
                            </div>

                            <!-- 加载状态 -->
                            <div
                                v-if="companyLoading"
                                class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 p-4"
                                style="top: 100%"
                            >
                                <span
                                    class="loading loading-spinner loading-sm text-primary"
                                ></span>
                                <span class="ml-2 text-sm">搜索中...</span>
                            </div>

                            <!-- 空状态 -->
                            <div
                                v-if="
                                    showCompanyDropdown &&
                                    filteredCompanies.length === 0 &&
                                    !companyLoading &&
                                    companySearchText
                                "
                                class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 p-4"
                                style="top: 100%"
                            >
                                <span class="text-sm text-gray-500"
                                    >未找到匹配的公司</span
                                >
                            </div>
                        </div>

                        <!-- 状态筛选 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium">状态</span>
                            </label>
                            <select
                                v-model="searchParams.status"
                                class="select select-bordered"
                                @change="searchContacts"
                            >
                                <option
                                    v-for="status in contactStatuses"
                                    :key="status.value"
                                    :value="status.value"
                                >
                                    {{ status.label }}
                                </option>
                            </select>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="form-control">
                            <div class="flex gap-2 mt-2">
                                <button
                                    @click="resetSearch"
                                    class="btn btn-outline flex-1"
                                    :disabled="loading"
                                >
                                    重置
                                </button>
                                <button
                                    @click="searchContacts"
                                    class="btn btn-primary flex-1"
                                    :disabled="loading"
                                >
                                    <span
                                        v-if="loading"
                                        class="loading loading-spinner loading-sm"
                                    ></span>
                                    搜索
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="text-center p-8">
                <span
                    class="loading loading-spinner loading-lg text-primary"
                ></span>
                <p class="mt-2 text-gray-600">加载联系人数据中...</p>
            </div>

            <!-- 联系人列表 -->
            <div v-else class="card bg-base-100 shadow-sm">
                <div class="card-body p-0">
                    <!-- 列表头部信息 -->
                    <div class="p-4 border-b border-base-300">
                        <div class="flex justify-between items-center">
                            <div>
                                <h2 class="text-lg font-semibold">
                                    联系人列表
                                </h2>
                                <p class="text-sm text-gray-500 mt-1">
                                    共 {{ pagination.page_total }} 页，{{
                                        pagination.page_items.length
                                    }}
                                    条记录
                                    <span class="ml-2">
                                        每页
                                        <select
                                            :value="pagination.page_size"
                                            @change="
                                                changePageSize(
                                                    parseInt(
                                                        $event.target.value,
                                                    ),
                                                )
                                            "
                                            class="select select-bordered select-xs mx-1"
                                        >
                                            <option value="10">10</option>
                                            <option value="20">20</option>
                                            <option value="50">50</option>
                                            <option value="100">100</option>
                                        </select>
                                        条
                                    </span>
                                </p>
                            </div>
                            <div
                                class="flex items-center gap-2 text-sm text-gray-500"
                            >
                                <div class="badge badge-success badge-sm"></div>
                                <span>正常</span>
                                <div class="badge badge-warning badge-sm"></div>
                                <span>离职</span>
                            </div>
                        </div>
                    </div>

                    <!-- 表格 -->
                    <div class="overflow-x-auto">
                        <table class="table table-zebra w-full">
                            <thead>
                                <tr class="bg-base-200">
                                    <th class="w-16">头像</th>
                                    <th class="w-42">联系人信息</th>
                                    <th class="w-32">职位</th>
                                    <th class="w-40">联系方式</th>
                                    <th>所属公司</th>
                                    <th class="w-24">状态</th>
                                    <th class="w-28">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr
                                    v-for="contact in pagination.page_items"
                                    :key="contact.id"
                                    class="hover cursor-pointer transition-colors duration-200 contact-row"
                                    @dblclick="contactDetail(contact)"
                                >
                                    <td>
                                        <div class="flex justify-center">
                                            <div
                                                v-if="contact.avatar"
                                                class="avatar"
                                            >
                                                <div
                                                    class="w-10 h-10 rounded-full"
                                                >
                                                    <img
                                                        :src="contact.avatar"
                                                        :alt="contact.name"
                                                    />
                                                </div>
                                            </div>
                                            <div
                                                v-else
                                                class="contact-avatar"
                                                :style="{
                                                    backgroundColor:
                                                        stringToColor(
                                                            contact.name,
                                                        ),
                                                }"
                                            >
                                                {{ contact.name.charAt(0) }}
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="flex flex-col">
                                            <span
                                                class="font-medium text-base"
                                                >{{ contact.name }}</span
                                            >
                                            <div
                                                class="flex items-center gap-1 mt-1"
                                            >
                                                <svg
                                                    class="w-3 h-3 text-gray-400"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                                                    />
                                                </svg>
                                                <span
                                                    class="text-xs text-gray-500"
                                                    >{{
                                                        contact.gender === 0
                                                            ? "男"
                                                            : contact.gender ===
                                                                1
                                                              ? "女"
                                                              : "未知"
                                                    }}</span
                                                >
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span
                                            class="badge badge-outline badge-sm"
                                            >{{
                                                contact.job_title ||
                                                "未设置职位"
                                            }}</span
                                        >
                                    </td>
                                    <td>
                                        <div class="flex flex-col gap-1">
                                            <div
                                                class="flex items-center gap-1"
                                            >
                                                <svg
                                                    class="w-3 h-3 text-gray-400"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"
                                                    />
                                                </svg>
                                                <span class="text-xs">{{
                                                    contact.phone ||
                                                    "未设置电话"
                                                }}</span>
                                            </div>
                                            <div
                                                class="flex items-center gap-1"
                                            >
                                                <svg
                                                    class="w-3 h-3 text-gray-400"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                                                    />
                                                </svg>
                                                <span class="text-xs">{{
                                                    contact.email ||
                                                    "未设置邮箱"
                                                }}</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="text-sm">{{
                                            contact.company_name || "未设置公司"
                                        }}</span>
                                    </td>
                                    <td>
                                        <span
                                            :class="[
                                                'badge badge-sm',
                                                getContactStatusInfo(
                                                    contact.status,
                                                ).badgeClass,
                                            ]"
                                        >
                                            {{
                                                getContactStatusInfo(
                                                    contact.status,
                                                ).label
                                            }}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="flex gap-1">
                                            <button
                                                class="btn btn-ghost btn-sm btn-circle tooltip"
                                                @click.stop="
                                                    contactDetail(contact)
                                                "
                                                data-tip="查看详情"
                                            >
                                                <svg
                                                    class="w-4 h-4"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"
                                                    />
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
                                                    />
                                                </svg>
                                            </button>
                                            <button
                                                class="btn btn-ghost btn-sm btn-circle tooltip"
                                                @click.stop="
                                                    editContact(contact)
                                                "
                                                data-tip="编辑联系人"
                                            >
                                                <svg
                                                    class="w-4 h-4"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="m14.304 4.844 2.852 2.852M7 7H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4.5m2.409-9.91a2.017 2.017 0 0 1 0 2.853l-6.844 6.844L8 14l.713-3.565 6.844-6.844a2.015 2.015 0 0 1 2.852 0Z"
                                                    />
                                                </svg>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 空状态 -->
                    <div
                        v-if="pagination.page_items.length === 0 && !loading"
                        class="text-center p-8"
                    >
                        <svg
                            class="w-16 h-16 mx-auto text-gray-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                            />
                        </svg>
                        <p class="mt-4 text-gray-500">暂无联系人数据</p>
                        <div class="mt-4 flex gap-2 justify-center">
                            <button
                                @click="resetSearch"
                                class="btn btn-outline btn-sm"
                            >
                                清除搜索条件
                            </button>
                            <button
                                @click="addContact"
                                class="btn btn-primary btn-sm"
                            >
                                添加第一个联系人
                            </button>
                        </div>
                    </div>

                    <!-- 分页控件 -->
                    <div
                        v-if="pagination.page_total > 1"
                        class="p-4 border-t border-base-300"
                    >
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-500">
                                第 {{ pagination.page_current }} 页，共
                                {{ pagination.page_total }} 页， 每页
                                {{ pagination.page_items.length }} 条记录
                            </span>
                            <div class="join">
                                <!-- 上一页 -->
                                <button
                                    class="join-item btn btn-sm"
                                    :disabled="pagination.page_current <= 1"
                                    @click="
                                        changePage(pagination.page_current - 1)
                                    "
                                >
                                    «
                                </button>

                                <!-- 页码按钮 -->
                                <button
                                    v-for="page in pageNumbers"
                                    :key="page"
                                    class="join-item btn btn-sm"
                                    :class="{
                                        'btn-active':
                                            page === pagination.page_current,
                                    }"
                                    @click="changePage(page)"
                                >
                                    {{ page }}
                                </button>

                                <!-- 下一页 -->
                                <button
                                    class="join-item btn btn-sm"
                                    :disabled="
                                        pagination.page_current >=
                                        pagination.page_total
                                    "
                                    @click="
                                        changePage(pagination.page_current + 1)
                                    "
                                >
                                    »
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { useRouter } from "vue-router";

const router = useRouter();

// 联系人接口定义 - 根据后端Contact结构调整
interface Contact {
    id: number;
    name: string;
    email: string;
    phone: string;
    gender: number; // 1-男，2-女
    birthday: string;
    job_title: string;
    avatar: string;
    company_id: number;
    status: number; // 联系人状态: 1-正常，2-离职
    personality: string;
    created_by: string;
    created_at: string;
    modified_by: string;
    modified_at: string;
    company_name: string;
}

// 公司接口定义
interface Company {
    id: number;
    name: string;
    type_id: number; // 公司类型: 1-材料生产单位，2-供应商，3-其他服务型
    status: number; // 公司状态: 1-正常，2-停业，3-注销
    address: string;
    staff_num: number; // 员工数量
    created_by: string;
    created_at: string;
    modified_by: string;
    modified_at: string;
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 分页接口定义
interface Pagination<T> {
    page_size: number;
    page_total: number;
    page_current: number;
    page_items: T[];
}

// 响应式数据
const contacts = ref<Contact[]>([]);
const companies = ref<Company[]>([]);
const loading = ref(false);
const error = ref("");

// 分页相关数据
const pagination = ref<Pagination<Contact>>({
    page_size: 10,
    page_total: 0,
    page_current: 1,
    page_items: [],
});

// 搜索参数 - 修改为与后端接口匹配的格式
const searchParams = ref({
    name: "", // 对应后端的 contact_name
    company_id: undefined as number | undefined, // 对应后端的 company_id (Optional)
    status: undefined as number | undefined, // 对应后端的 status (Optional)
});

// 公司搜索相关数据
const companySearchText = ref("");
const showCompanyDropdown = ref(false);
const filteredCompanies = ref<Company[]>([]);
const companyLoading = ref(false);

// 防抖定时器
let searchDebounceTimer: NodeJS.Timeout | null = null;

// 联系人状态选项
const contactStatuses = [
    { value: undefined, label: "全部状态" },
    { value: 0, label: "离职" },
    { value: 1, label: "在职" },
    { value: 2, label: "试用期" },
    { value: 3, label: "退休" },
];

// 从API加载联系人数据（支持分页和搜索）
async function loadContacts(page: number = 1) {
    loading.value = true;
    error.value = "";

    try {
        // 准备API参数
        const apiParams = {
            contact_name:
                searchParams.value.name.trim() !== ""
                    ? searchParams.value.name.trim()
                    : undefined,
            company_id: searchParams.value.company_id,
            status: searchParams.value.status,
            page_current: page,
            page_size: pagination.value.page_size,
        };

        console.log("调用 list_contact API，参数:", apiParams);

        // 调用后端API
        const response: ApiResponse<Pagination<Contact>> = await invoke(
            "list_contact",
            apiParams,
        );

        if (response.status_code === 200 && response.data) {
            // 成功获取数据
            pagination.value = response.data;
            contacts.value = response.data.page_items;

            console.log(
                `成功加载 ${response.data.page_items.length} 条联系人数据`,
            );
        } else {
            // API返回错误
            error.value = response.message || "获取联系人列表失败";
            console.error("获取联系人列表失败:", response);

            // 设置空数据
            contacts.value = [];
            pagination.value.page_items = [];
            pagination.value.page_total = 0;
        }
    } catch (err) {
        error.value = "网络请求失败，请检查连接";
        console.error("调用联系人列表API失败:", err);

        // 设置空数据
        contacts.value = [];
        pagination.value.page_items = [];
        pagination.value.page_total = 0;
    } finally {
        loading.value = false;
    }
}

// 刷新数据（重置到第一页）
async function refreshData() {
    pagination.value.page_current = 1;
    await loadContacts(1);
}

// 搜索数据（重置到第一页）
async function searchContacts() {
    pagination.value.page_current = 1;
    await loadContacts(1);
}

// 重置搜索条件
function resetSearch() {
    searchParams.value = {
        name: "",
        company_id: undefined,
        status: undefined,
    };
    companySearchText.value = "";
    // 重置后重新加载第一页数据
    pagination.value.page_current = 1;
    loadContacts(1);
}

// 改变页码
function changePage(page: number) {
    if (page < 1 || page > pagination.value.page_total) return;
    pagination.value.page_current = page;
    loadContacts(page);
}

// 改变每页大小
function changePageSize(size: number) {
    pagination.value.page_size = size;
    pagination.value.page_current = 1;
    loadContacts(1);
}

// 生成页码数组（用于分页控件）
const pageNumbers = computed(() => {
    const current = pagination.value.page_current;
    const total = pagination.value.page_total;

    if (total <= 1) return [];

    const pages = [];
    const maxVisiblePages = 5;

    let startPage = Math.max(1, current - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(total, startPage + maxVisiblePages - 1);

    // 调整起始页码，确保显示maxVisiblePages个页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
        pages.push(i);
    }

    return pages;
});

// 公司搜索处理（带防抖）
async function handleCompanySearch() {
    if (searchDebounceTimer) {
        clearTimeout(searchDebounceTimer);
    }

    searchDebounceTimer = setTimeout(async () => {
        const searchText = companySearchText.value.trim();

        if (searchText === "") {
            filteredCompanies.value = [];
            showCompanyDropdown.value = false;
            return;
        }

        companyLoading.value = true;
        showCompanyDropdown.value = true;

        try {
            const response: ApiResponse<Company[]> = await invoke(
                "list_company_by_name",
                { name: searchText },
            );

            if (response.status_code === 200 && response.data) {
                filteredCompanies.value = response.data;
            } else {
                console.error("搜索公司失败:", response.message);
                filteredCompanies.value = [];
                error.value = "搜索公司失败，请稍后重试";
            }
        } catch (err) {
            console.error("调用公司搜索API失败:", err);
            filteredCompanies.value = [];
            error.value = "搜索公司失败，请检查网络连接";
        } finally {
            companyLoading.value = false;
        }
    }, 300);
}

// 选择公司
function selectCompany(company: Company) {
    searchParams.value.company_id = company.id;
    companySearchText.value = company.name;
    showCompanyDropdown.value = false;

    // 将选中的公司添加到公司列表中，以便后续查找
    if (!companies.value.find((c) => c.id === company.id)) {
        companies.value.push(company);
    }
}

// 隐藏下拉框
function hideCompanyDropdown() {
    setTimeout(() => {
        showCompanyDropdown.value = false;
    }, 200);
}

// 获取公司名称
function getCompanyName(companyId: number): string {
    const company = companies.value.find((c) => c.id === companyId);
    return company ? company.name : `公司ID: ${companyId}`;
}

// 获取联系人状态标签和样式
function getContactStatusInfo(status: number) {
    const statusObj = contactStatuses.find((s) => s.value === status);
    if (!statusObj) return { label: "未知状态", badgeClass: "badge-neutral" };

    const badgeClasses: Record<number, string> = {
        1: "badge-success", // 正常 - 绿色
        2: "badge-warning", // 离职 - 黄色
    };

    return {
        label: statusObj.label,
        badgeClass: badgeClasses[status] || "badge-neutral",
    };
}

// 生成头像背景色
function stringToColor(str: string): string {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }

    const colors = [
        "#4f46e5",
        "#0ea5e9",
        "#10b981",
        "#f59e0b",
        "#ef4444",
        "#8b5cf6",
        "#ec4899",
        "#06b6d4",
    ];

    return colors[Math.abs(hash) % colors.length];
}

// 路由导航
function editContact(contact: Contact) {
    router.push({
        name: "contactdetail",
        params: { id: contact.id.toString() },
    });
}

function addContact() {
    router.push({
        name: "contactdetail",
        params: { id: "New" },
    });
}

function contactDetail(contact: Contact) {
    router.push({
        name: "contactdetail",
        params: { id: contact.id.toString() },
    });
}

// 页面加载时初始化
onMounted(() => {
    // 初始时不加载公司数据，等待用户搜索
    companies.value = [];
    loadContacts(1);
});
</script>

<style scoped>
.contact-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    color: white;
}

.contact-row:hover {
    background-color: rgba(0, 0, 0, 0.02);
    cursor: pointer;
}

/* 确保表格在小屏幕上也能正常显示 */
@media (max-width: 768px) {
    .table {
        font-size: 0.875rem;
    }

    .badge {
        font-size: 0.75rem;
    }

    .join .btn {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
        min-height: 2rem;
        height: 2rem;
    }
}

/* 确保搜索表单元素对齐 */
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}

/* 确保搜索区域网格对齐 */
.grid.items-end {
    align-items: end;
}

/* 分页控件样式优化 */
.join .btn {
    min-width: 2.5rem;
}
</style>
